package org.jflame.commons.crypto;

import org.jflame.commons.crypto.CipherArgs.AsymmetricArgs;
import org.jflame.commons.crypto.Transformation.OpMode;
import org.jflame.commons.crypto.Transformation.Padding;

import java.security.KeyPair;

/**
 * 非对称加密算法父类
 * 
 * @author charles.zhang
 */
public abstract class AsymmetricEncryptor extends BaseEncryptor {

    public AsymmetricEncryptor(Transformation tf) throws EncryptException {
        super(tf);
    }

    public AsymmetricEncryptor(Transformation tf, String providerName) throws EncryptException {
        super(tf, providerName);
    }

    @Override
    public boolean isSupport() {
        return transformation.isAsymmetric();
    }

    public AsymmetricArgs buildArgs(final String publicKeyBase64Str, final String privateKeyBase64Str)
            throws EncryptException {
        return new AsymmetricArgs(transformation.getAlg(), publicKeyBase64Str, privateKeyBase64Str);
    }

    public AsymmetricArgs buildArgs(final KeyPair keyPair) throws EncryptException {
        return new AsymmetricArgs(keyPair);
    }

    public static AsymmetricEncryptor of(Transformation tf) throws EncryptException {
        return AsymmetricEncryptor.of(tf.getAlg(), tf.getMode(), tf.getPadding());
    }

    public static AsymmetricEncryptor of(Alg alg, OpMode mode, Padding padding) throws EncryptException {
        if (alg == Alg.RSA) {
            return new RSAEncryptor(new Transformation(alg, mode, padding));
        } else if (alg == Alg.SM2) {
            return new SM2Encryptor();
        } else {
            throw new EncryptException("不支持的非对称加密算法");
        }
    }
}
